<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="提示词名称" prop="promptName">
        <el-input
          v-model="queryParams.promptName"
          placeholder="请输入提示词名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="promptVersion">
        <el-input
          v-model="queryParams.promptVersion"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="提示词状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:contractPrompt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:contractPrompt:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="promptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="提示词名称" align="center" prop="promptName" />
      <el-table-column label="版本号" align="center" prop="promptVersion" />
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true"/>
      <el-table-column label="关联类型" align="center" prop="typeNames" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag
            v-for="typeName in scope.row.typeNames"
            :key="typeName"
            size="mini"
            style="margin-right: 5px;"
          >{{ typeName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:contractPrompt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewContent(scope.row)"
          >查看内容</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:contractPrompt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同提示词对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="提示词名称" prop="promptName">
          <el-input v-model="form.promptName" placeholder="请输入提示词名称" />
        </el-form-item>
        <el-form-item label="版本号" prop="promptVersion">
          <el-input v-model="form.promptVersion" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联类型" prop="typeIds">
          <treeselect
            v-model="form.typeIds"
            :options="contractTypeOptions"
            :normalizer="normalizer"
            :show-count="true"
            multiple
            placeholder="请选择关联的合同类型"
          />
        </el-form-item>
        <el-form-item label="任务目标" prop="taskObjective">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入任务目标"
            v-model="form.taskObjective">
          </el-input>
        </el-form-item>
        <el-form-item label="输出格式" prop="outputFormat">
          <el-input
            type="textarea"
            :rows="6"
            placeholder="请输入JSON格式的输出结构"
            v-model="form.outputFormat">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看提示词内容对话框 -->
    <el-dialog title="提示词内容" :visible.sync="viewDialogVisible" width="780px" append-to-body>
      <div class="prompt-content">
        <div class="content-section">
          <h4>任务目标</h4>
          <pre>{{ viewForm.taskObjective }}</pre>
        </div>
        <div class="content-section">
          <h4>输出格式</h4>
          <pre v-if="isValidJson(viewForm.outputFormat)" v-html="formatJson(viewForm.outputFormat)"></pre>
          <pre v-else>{{ viewForm.outputFormat }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContractPrompt, getContractPrompt, delContractPrompt, addContractPrompt, updateContractPrompt,
         getPromptContent } from "@/api/system/contractPrompt";
import { listContractType } from "@/api/system/contractType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ContractPrompt",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同提示词表格数据
      promptList: [],
      // 合同类型树选项
      contractTypeOptions: [],
      // 类型ID到名称的映射
      typeIdToName: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promptName: null,
        promptVersion: null,
        status: null
      },
      // 表单参数
      form: {
        promptId: null,
        promptName: null,
        promptVersion: null,
        description: null,
        typeIds: [],
        status: "0",
        taskObjective: '',
        outputFormat: ''
      },
      // 表单校验
      rules: {
        promptName: [
          { required: true, message: "提示词名称不能为空", trigger: "blur" }
        ],
        promptVersion: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        typeIds: [
          { required: true, message: "请选择关联的合同类型", trigger: "change" }
        ],
        taskObjective: [
          { required: true, message: "任务目标不能为空", trigger: "blur" }
        ],
        outputFormat: [
          { required: true, message: "输出格式不能为空", trigger: "blur" }
        ]
      },
      // 查看内容对话框
      viewDialogVisible: false,
      // 查看的内容
      viewForm: {
        taskObjective: '',
        outputFormat: ''
      },
    };
  },
  created() {
    this.getList();
    // 获取合同类型列表
    this.getTreeselect();
  },
  methods: {
    /** 转换合同类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeId,
        label: node.typeName,
        children: node.children
      };
    },
    /** 查询合同类型下拉树结构 */
    getTreeselect() {
      listContractType().then(response => {
        this.contractTypeOptions = response.data;
        // 构建类型ID到名称的映射
        this.buildTypeIdNameMap(response.data);
      });
    },
    /** 构建类型ID到名称的映射 */
    buildTypeIdNameMap(types) {
      types.forEach(type => {
        this.typeIdToName[type.typeId] = type.typeName;
        if (type.children && type.children.length > 0) {
          this.buildTypeIdNameMap(type.children);
        }
      });
    },
    /** 查询合同提示词列表 */
    getList() {
      this.loading = true;
      listContractPrompt(this.queryParams).then(response => {
        // 处理类型名称显示
        this.promptList = response.rows.map(item => {
          if (item.typeIds) {
            item.typeNames = item.typeIds
              .map(typeId => this.typeIdToName[typeId])
              .filter(name => name);
          } else {
            item.typeNames = [];
          }
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        promptId: null,
        promptName: null,
        promptVersion: null,
        description: null,
        typeIds: [],
        status: "0",
        taskObjective: '',
        outputFormat: ''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.promptId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同提示词";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const promptId = row.promptId || this.ids;
      if (!promptId) {
        this.$message.error('提示词ID不能为空');
        return;
      }

      // 先重置表单
      this.form = {
        promptId: null,
        promptName: null,
        promptVersion: null,
        description: null,
        typeIds: [],
        status: "0",
        taskObjective: '',
        outputFormat: ''
      };

      // 获取基本信息
      getContractPrompt(promptId).then(response => {
        if (response && response.data) {
          // 合并数据，保留默认值
          this.form = {
            ...this.form,
            ...response.data
          };

          // 获取提示词内容
          getPromptContent(promptId).then(res => {
            if (res && res.data) {
              this.form.taskObjective = res.data.taskObjective || '';
              this.form.outputFormat = res.data.outputFormat || '';
            }
            // 不管内容获取是否成功，都显示对话框
            this.open = true;
            this.title = "修改合同提示词";
          }).catch(error => {
            console.error('获取提示词内容失败:', error);
            this.$message.error('获取提示词内容失败');
            // 即使获取内容失败，也显示对话框
            this.open = true;
            this.title = "修改合同提示词";
          });
        } else {
          this.$message.error('获取提示词信息失败');
        }
      }).catch(error => {
        console.error('获取提示词信息失败:', error);
        this.$message.error('获取提示词信息失败');
      });
    },
    /** 查看内容按钮操作 */
    handleViewContent(row) {
      const promptId = row.promptId;
      getPromptContent(promptId).then(res => {
        if (res && res.data) {
          this.viewForm.taskObjective = res.data.taskObjective || '';
          this.viewForm.outputFormat = res.data.outputFormat || '';
          this.viewDialogVisible = true;
        }
      }).catch(error => {
        console.error('获取提示词内容失败:', error);
        this.$message.error('获取提示词内容失败');
      });
    },
    
    /** 判断字符串是否为有效的JSON */
    isValidJson(str) {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    },

    /** 格式化JSON字符串 */
    formatJson(str) {
      try {
        const obj = JSON.parse(str);
        return JSON.stringify(obj, null, 2)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;')
          .replace(/'/g, '&#39;')
          .replace(/\n/g, '<br>')
          .replace(/ /g, '&nbsp;');
      } catch (e) {
        return str;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.promptId != null) {
            updateContractPrompt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContractPrompt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const promptIds = row.promptId || this.ids;
      this.$modal.confirm('是否确认删除提示词编号为"' + promptIds + '"的数据项？').then(function() {
        return delContractPrompt(promptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: inherit;
}

.prompt-content {
  padding: 10px;
}

.content-section {
  margin-bottom: 20px;
}

.content-section h4 {
  margin-bottom: 10px;
  color: #606266;
}

.content-section pre {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
}
</style>
